# -*- coding: utf-8 -*-
from flask import Blueprint,request,jsonify,make_response,redirect,g
from common.models.User import User
from common.libs.user.UserService import  UserService
from  application import  app
from common.libs.Helper import osp_render

from common.libs.UrlManager import UrlManager
from application import  db
import  json
route_user = Blueprint( 'user_page',__name__ )

@route_user.route( "/login", methods=["GET","POST"] )
def login():
    if request.method == "GET":
        return osp_render("user/login.html")
    resq = {'code': 200,
            'msg': '欢迎进入外卖自提柜信息管理平台!',
            'data': {}
            }
    req = request.values;
    login_name = req["login_name"] if "login_name" in req else ""
    login_pwd = req["login_pwd"] if "login_pwd" in req else ""
    # 对登录参数进行有效性校验
    if login_name is None or len(login_name) < 1:
        resq['code'] = -1
        resq['msg'] = "Please write the right name~"
        return jsonify(resq)

    if login_pwd is None or len(login_pwd) < 1:
        resq['code'] = -1
        resq['msg'] = 'Please write the right password~'
        return jsonify(resq)
    # User表查询
    user_info = User.query.filter_by(login_name=login_name).first()  # 因为login_name唯一，所以取一条记录即可
    if not user_info:
        resq['code'] = -1
        resq['msg'] = 'Please write the right name and password ~'
        return jsonify(resq)
    '''
        校验密码：
        genePwd两个参数，一个是用户输入的字符串，一个是随机加密字符串
    '''
    if user_info.login_pwd != UserService.genePwd(login_pwd, user_info.login_salt):
        resq['code'] = -1
        resq['msg'] = 'Please write the right name and password~'
        return jsonify(resq)
    if user_info.status != 1:
        resq['code'] = -1
        resq['msg'] = '账号已经被禁用，请联系管理员处理~'
        return jsonify(resq)
    #登录态的实现
    #获取返回值:Json的序列化
    response = make_response(json.dumps(resq))
    #自定义页面Cookie
    response.set_cookie(app.config['AUTH_COOKIE_NAME'],
                        "%s#%s" % (UserService.geneAuthCode(user_info), user_info.uid))
    return response
    return jsonify(resq)

@route_user.route( "/edit" ,methods=["GET","POST"])
def edit():
    if request.method == "GET":
        return osp_render("user/edit.html", {'current': 'edit'})
        # 0、定义回滚值
    resq = {'code': 200, 'msg': "操作成功~", 'data': {}}
    # 1、参数获取
    req = request.values  # 从request获取所有的请求值
    nickname = req['nickname'] if 'nickname' in req else ''
    email = req['email'] if 'email' in req else ''
    # 2、判断参数合法性
    if nickname is None or len(nickname) < 1:
        resq['code'] = -1
        resq['msg'] = "请输入符合规范的姓名"
        return jsonify(resq)

    if email is None or len(email) < 1:
        resq['code'] = -1
        resq['msg'] = "请输入符合规范的邮箱"
        return jsonify(resq)
    # 3、更新当前用户数据，当前用户不需要查询数据库，因为已经查询出
    user_info = g.current_user
    user_info.nickname = nickname
    user_info.email = email

    # 4、统一提交(事务提交）
    db.session.add(user_info)
    db.session.commit()

    return jsonify(resq)  # 返回给客户端提示更改成功

@route_user.route( "/reset-pwd",methods=["GET","POST"])
def resetPwd():
    if request.method == "GET":
         return osp_render( "user/reset_pwd.html",{'current':'reset-pwd'} )
    resq = {'code': 200, 'msg': "操作成功~", 'data': {}}
    # 1、从request获取所有的请求值
    req = request.values
    new_password = req['new_password'] if 'new_password' in req else ''
    old_password = req['old_password'] if 'new_password' in req else ''
    # 2、参数有效性判断
    if old_password is None or len(old_password) < 6:
        resq['code'] = -1
        resq['msg'] = '请输入符合规范的原密码~'
        return jsonify(resq)
    if new_password is None or len(new_password) < 6:
        resq['code'] = -1
        resq['msg'] = '请输入符合规范的新密码~'
        return jsonify(resq)
    if old_password == new_password:
        resq['code'] = -1
        resq['msg'] = '请重新输入，新密码和原密码不能相同！'
        return jsonify(resq)
    # 3、密码更改
    user_info = g.current_user
    user_info.login_pwd = UserService.genePwd(new_password, user_info.login_salt)

    # 4、写入数据库，并统一提交
    db.session.add(user_info)
    db.session.commit()
    # 5、更新Cookie值
    response = make_response(json.dumps(resq))
    response.set_cookie(app.config['AUTH_COOKIE_NAME'], "%s#%s" % (UserService.geneAuthCode(user_info), user_info.uid))
    return response

@route_user.route("/logout")#不需要写user因为user的前缀已经统一写
def logout():#只需要
    response = make_response(redirect(UrlManager.buildUrl('/user/login')))
    response.delete_cookie(app.config['AUTH_COOKIE_NAME'])
    return  response